<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-粗纱用料`"
		width="1100px"
		:show-content-loading="showLoading"
		:save-btn-loading="saveBtnLoading"
		append-to-body
		:show-confirm-btn="false"
		:show-save-btn="true"
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-save="onConfirmBtn('save')"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="90px" :show-message="false">
			<el-row ref="box1">
				<!--<el-col :span="8">
					<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
						<el-select v-model="ruleForm.workshopId" class="width-100-percent" placeholder="区域">
							<el-option
								v-for="item in workshopList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>-->
				<el-col :span="8">
					<el-form-item class="margin-bottom-10" label="日期" prop="belongDate">
						<jk-date-picker v-model="ruleForm.belongDate" type="date" size="medium" placeholder="日期" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item class="margin-bottom-10" label="人员" prop="empId">
						<remote-search-emp-input
							placeholder="人员"
							only-key="empId"
							query-name="empName"
							:form-data="ruleForm"
							@on-select="onSelectEmpChange"
						></remote-search-emp-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<jk-table border :data="ruleForm.subTitleList" :height="dialogTableHeight - 20">
			<vxe-column title="操作" align="center" field="processName" :width="80">
				<template slot="header">
					<el-button type="text" size="mini" @click="onAddBtn">添加</el-button>
				</template>
				<template slot-scope="scope">
					<el-button type="default" icon="el-icon-delete" size="mini" @click="ruleForm.subTitleList.splice(scope.rowIndex, 1)"></el-button>
				</template>
			</vxe-column>
			<vxe-column title="系列" align="center" field="subTitle" :width="160">
				<template slot-scope="scope">
					<div class="flex-start-center">
						<el-input v-model="scope.row.subTitle" size="mini" placeholder="系列" class="item-gap" />
						<el-tag class="el-icon-plus flex-between-center" type="info" effect="plain" @click="onAddMachineBtn(scope)"></el-tag>
					</div>
				</template>
			</vxe-column>
			<vxe-column title="品种明细" align="left" field="productUseCommunicationItemList" :min-width="100">
				<template slot-scope="scope">
					<el-row
						v-for="(item, index) in scope.row.productUseCommunicationItemList"
						:key="index"
						style="margin: 2px 0;"
						:gutter="4"
						class="flex-start-center"
					>
						<el-col :span="7" class="flex-start-center">
							<el-tag type="info" effect="plain" class="item-gap el-icon-minus" plain @click="ruleForm.subTitleList[scope.rowIndex].productUseCommunicationItemList.splice(index, 1)"></el-tag>
							<remote-search-product-input
								placeholder="品种"
								size="mini"
								default-stock-type="FINISHED_PRODUCT"
								only-key="productId"
								query-name="productName"
								:form-data="item"
								@on-select="onSelectProductChange($event, scope.rowIndex, index)"
							></remote-search-product-input>
						</el-col>
						<el-col :span="5">
							<remote-search-batch-code-input
								:disabled="!item.productId"
								size="mini"
								placeholder="批号"
								only-key="batchId"
								query-name="batchCode"
								:form-data="item"
								@on-select="onSelectBatchChange($event, scope.rowIndex, index)"
							></remote-search-batch-code-input>
						</el-col>
						<el-col :span="4">
							<el-input v-model="item.color" size="mini" placeholder="管色" />
						</el-col>
						<el-col :span="4">
							<el-input v-model="item.dosage" size="mini" placeholder="用量" />
						</el-col>
						<el-col :span="4">
							<el-input v-model="item.extendText" size="mini" placeholder="订单还需" />
						</el-col>
					</el-row>
				</template>
			</vxe-column>
		</jk-table>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        productionProductUseCommunicationCreate,
        productionProductUseCommunicationUpdate,
        productionProductUseCommunicationGet
    } from '../../../api/production/csUseMaterialStatistics';
    import checkboxMachineDialog from '../../schedule/empMachine/components/checkbox-machine-dialog';
    import remoteSearchEmpInput from '../../production/order/components/remote-search-emp-input';
    import remoteSearchProductInput from '../../production/order/components/remote-search-product-input';
    import remoteSearchBatchCodeInput
        from '../../production/qhPrd/productConfigCotton/components/remote-search-batch-code-input';
    import { formatDate } from '../../../utils/jk/jk-tool';
    export default {
        name: 'CsUseMaterialStatistics',
        components: {
            remoteSearchBatchCodeInput,
            remoteSearchProductInput,
            checkboxMachineDialog,
            remoteSearchEmpInput
        },
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            defaultTypeCode: {
                type: String,
                default: ''
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                workshopList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    belongDate: '',
                    empId: null,
                    empName: '',
                    workshopId: null,
                    subTitleList: []
                },
                rules: {
                    belongDate: [{ required: true, trigger: 'change' }],
                    empId: [{ required: true, trigger: 'change' }],
                    colorValue: [{ required: true, trigger: 'change' }],
                    workshopId: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onSelectBatchChange(e, rowIndex, cellIndex) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'batchId', e.id);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'batchCode', e.batchCode);
                }
            },
            onSelectProductChange(e, rowIndex, cellIndex) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productId', e.id);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productCode', e.code);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productName', e.name);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productModels', e.models);
                }
            },
            onSelectEmpChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'empId', e.id);
                    this.$set(this.ruleForm, 'empName', e.name);
                }
            },
            onAddMachineBtn({ rowIndex }) {
                this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList.push({
                    'batchCode': '',
                    'batchId': 0,
                    'color': '',
                    'dosage': '',
                    'extendText': '',
                    'productCode': '',
                    'productId': 0,
                    'productModels': '',
                    'productName': '',
                    'remark': '',
                    'subTitle': ''
                });
            },
            onAddBtn() {
                this.ruleForm.subTitleList.push({
                    subTitle: null,
                    productUseCommunicationItemList: []
                });
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                const item = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopCode = item.code;
                params.workshopName = item.name;
                params.subTitleList.forEach(x => {
                });
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                // 新增
                if (!this.dataId) {
                    this.ruleForm.id = null;
                    productionProductUseCommunicationCreate(this.getParamData()).then(res => {
                        this.saveBtnLoading = false;
                        if (res.data.status === 200) {
                            this.$tipsBar(this, 'save');
                            // 生产订单-远程搜索组件用到，需返回ID
                            this.$emit('on-finish', res.data.res);
                        }
                    });
                    return;
                }

                // 编辑
                productionProductUseCommunicationUpdate(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onConfirmBtn(type) {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionProductUseCommunicationGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                    this.$set(this.ruleForm, 'empId', this.$store.state.user.empInfo.id);
                    this.$set(this.ruleForm, 'empName', this.$store.state.user.empInfo.name);
                    this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                }
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
